<template>
  <div>
    <h2 style="text-align: center;">你好！ {{userInfo.username}} 同学！</h2>
    <el-form
      ref="userCenterFromRef"
      :model="userCenterFrom"
      status-icon
      :rules="rules"
      label-width="120px"
      :size="formSize"
      class="demo-ruleForm"
    >
      <el-form-item label="旧密码" prop="currentPass">
        <el-input v-model="userCenterFrom.currentPass" type="password" />
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input v-model="userCenterFrom.password" type="password" />
      </el-form-item>
      <el-form-item label="确认新密码" prop="checkpassword">
        <el-input v-model="userCenterFrom.checkpassword" type="password" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(userCenterFromRef)"
          >确定</el-button
        >
        <el-button @click="resetForm(userCenterFromRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, onMounted } from "vue";
import {
  Action,
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
} from "element-plus";

// 定义表单数据结构
interface ruleForm {
  currentPass: string;
  password: string;
  checkpassword: string;
}
// 定义表单大小 默认大小
const formSize = ref("default");
// 创建表单 ref 实例
const userCenterFromRef = ref<FormInstance>();
// 创建表单对象实例，实现数据的双向绑定
const userCenterFrom = reactive<ruleForm>({
  currentPass: "",
  password: "",
  checkpassword: "",
});

// 用户信息接口
interface UserInfo {
  id?: number;
  username?: string;
  avatar?: string;
}
const userInfo = ref<UserInfo>({});

// 获取全局axios变量
const { proxy } = getCurrentInstance() as any;
// 获取用户信息
function getUserName() {
  proxy.$axios.get("/sys/userInfo").then((res: any) => {
    userInfo.value = res.data.data;
  });
}

// 是否输入旧密码验证
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入旧密码！"));
  } else {
    callback();
  }
};
// 是否输入新密码验证
function validatePass2(rule: any, value: any, callback: any) {
  if (value === "") {
    callback(new Error("请输入新密码！"));
  } else if (value === userCenterFrom.currentPass) {
    callback(new Error("新密码不能与旧密码相同！"));
  } else {
    callback();
  }
}
// 两次密码输入是否一致
function validatePass3(rule: any, value: any, callback: any) {
  if (value === "") {
    callback(new Error("请再次输入新密码！"));
  } else if (value !== userCenterFrom.password) {
    callback(new Error("两次密码输入不一致！"));
  } else {
    callback();
  }
}

// 定义表单验证规则
const rules = reactive<FormRules<typeof userCenterFrom>>({
  currentPass: [{ validator: validatePass, trigger: "blur" }],
  password: [{ validator: validatePass2, trigger: "blur" }],
  checkpassword: [{ validator: validatePass3, trigger: "blur" }],
});

// 表单提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      // 表单验证成功
      ElMessageBox.alert("确定修改密码？", "确认信息", {
        confirmButtonText: "确定",
        type: "warning", // 弹窗类型 警告
        callback: (action: Action) => {
          // 回调函数，用户点击确认后触发
          if (action === "confirm") {
            // 提交信息并接受后端返回的信息
            proxy.$axios
              .post("/sys/user/updatePass", userCenterFrom)
              .then((res: any) => {
                ElMessage({
                  type: "success",
                  message: res.data.msg, // 读取后端返回的信息
                  duration: 1000, // 控制弹出时长
                });
              });
          }
        },
      });
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

// 表单重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 挂载时调用获取用户信息
onMounted(function () {
  getUserName();
});
</script>

<style scoped>
.demo-ruleForm {
  width: 400px;
  margin: 0 auto;
  margin-top: 70px;
}

.el-button {
  margin-left: 50px;
}
</style>
